<!--选择表单绑定的服务-->
<template>
  <!--  <pre>
        {{ formConfig}}
    </pre>-->

  <div>
    <el-form-item :label="'服务调用'">
      <el-switch v-model="optionModel.service.enabled" @change="handleSwitchChange"></el-switch>
    </el-form-item>
    <el-form-item v-if="!!optionModel.service.enabled" :label="'服务名称'">
      <el-select v-model="currentServiceId" filterable clearable collapse-tags-tooltip @change="onServiceChange">
        <el-option v-for="(item, idx) in formServices" :key="idx" :label="item.service.name"
                   :value="item.id"></el-option>
      </el-select>
    </el-form-item>
  </div>

</template>

<script setup lang="ts">
import { FormDesigner } from '@/types/form'
import { ServiceVersionVOType } from '@coolphk/shared-types/low-code'
import eventBus from '@/utils/event-bus'
import { FieldOptionsMap, FieldType, FieldWidgetType } from '@/components/form-designer/widget-panel/basic-fields'
import { ElMessageBox } from 'element-plus'
import { SERVICE_OPERATION } from '@/utils/constants'

defineOptions({
  name: 'service-editor',
})
type Props<T extends FieldType> = {
  designer: FormDesigner
  selectedWidget: FieldWidgetType<T>,
  optionModel: FieldOptionsMap[T],
}
const props = defineProps<Props<FieldType>>()
const currentServiceId = computed({
  get() {
    return props.optionModel.service.id
  },
  set(val) {
    props.optionModel.service.id = val
  },
})

const formServices = computed<ServiceVersionVOType[]>(() => {
  return props.designer.formConfig?.serviceVersionVOs?.map((svvo: ServiceVersionVOType) => {
    console.log('formServices', svvo)
    return svvo
  })
})
const onCreated = () => {
  eventBus.$on(SERVICE_OPERATION.UPDATE, ({ oldId, newId }) => {
    console.log('update-service-data', oldId, newId)
    if (props.optionModel.service.id == oldId) {
      props.optionModel.service.id = newId
    }
  })
  // TODOLIU 服务列表删除指定服务 source：data-source-setting/index.vue
  eventBus.$on(SERVICE_OPERATION.DELETE, (id) => {
    if (props.optionModel.service.id == id) {
      initOptions()
      console.log('delete-service-data', id)
    }
  })
}
const initOptions = () => {
  //this.field.options.optionItems = deepClone(options)
  props.optionModel.optionItems = []
  props.optionModel.labelKey = 'label'
  props.optionModel.valueKey = 'value'
  props.optionModel.service.id = ''
}
const handleSwitchChange = (val) => {
  if (val) {
    // this.optionModel.childForm && (this.optionModel.childForm = false)
    //关闭数据源
    props.optionModel?.dsEnabled && (props.optionModel.dsEnabled = false)
    if (props?.selectedWidget?.type === 'select') {
      props.optionModel.optionItems = []
    }
  }
}

const onServiceChange = (val) => {
  console.log('onServiceChange', val)
  switch (props.selectedWidget.type) {
    case 'data-table':
      const dataTableOptions = props.optionModel as FieldOptionsMap['data-table']
      const updateServiceAndColumns = (currentFSVVO) => {
        dataTableOptions.service.id = val
        dataTableOptions.tableColumns.splice(0, dataTableOptions.tableColumns.length)
        currentFSVVO.outputModelTree[0]?.children?.forEach((child) => {
          dataTableOptions.tableColumns.push({
            label: child.label,
            prop: child.key,
            width: '150',
            align: 'center',
            fixed: '',
            widgetList: [],
          })
        })
        const firstRowData = {}
        dataTableOptions.tableColumns.forEach((column) => {
          firstRowData[column.prop] = ''
        })
        dataTableOptions.tableData = [firstRowData]
        // console.log('firstRowData', firstRowData)
      }
      if (val) {
        const currentFSVVO = props.designer.formConfig.serviceVersionVOs.find((svvo) => svvo.id === val)
        if (dataTableOptions.service.id && dataTableOptions.tableColumns.length > 0) {
          ElMessageBox.confirm('是否清除列绑定？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            updateServiceAndColumns(currentFSVVO)
          })
        } else {
          updateServiceAndColumns(currentFSVVO)
        }

      } else {
        // if (dataTableModel.service.id) {
        ElMessageBox.confirm('是否清除列绑定？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          dataTableOptions.tableColumns.splice(0, dataTableOptions.tableColumns.length)
          dataTableOptions.service.id = ''
          dataTableOptions.tableData.splice(0, dataTableOptions.tableData.length)
        })
        // }
      }
      break
    default:
      break
  }
}
onUnmounted(() => {
  eventBus.$off(SERVICE_OPERATION.UPDATE)
  eventBus.$off(SERVICE_OPERATION.DELETE)
})
onCreated()
</script>

<style scoped></style>
